import React, { useState } from 'react'
import { IndexBar, Cell, Button } from 'react-vant';
import { Search } from 'react-vant';
import cityData from '../../mock/allcity.json'
import { debounce } from 'lodash'
interface ListItem {
	name: string
	key: string
}

type CityListType = [string, ListItem[]]

const golBalKeys: CityListType[] = Object.entries(cityData)

type Props = {}

const Index = (props: Props) => {
	const [keys, setKeys] = useState(golBalKeys)

	const onChange = debounce((value: string) => {
		const result = golBalKeys.filter((v) => {
			// 过滤键名
			if (v[0] === '热门城市') return false
			const exist = v[1].some((item) => item.name.includes(value))
			return exist
		}).map((v) => {
			// 过滤键值
			return [v[0], v[1].filter((v) => v.name.includes(value))]
		})
		// 断言
		setKeys(result as CityListType[])
	}, 400)

	return (
		<div>
			<Search onChange={(value: string) => onChange(value)}></Search>
			<IndexBar>
				{
					keys.map((v, i) => {
						return (
							<div key={i}>
								<IndexBar.Anchor index={v[0]} />
								{
									v[1].map((item, index) => {
										return (
											<div key={index}>
												<Cell title={item.name} />
											</div>
										)
									})
								}
							</div>
						)
					})
				}
			</IndexBar>
		</div>
	)
}

export default Index